package com.oraclefmw.crusher.core;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.BlockingQueue;

public class FileSplitter implements Runnable {

	private BlockingQueue<Fragment> queue;
	private File file;
	private int chunkSize;
	
	public FileSplitter(BlockingQueue<Fragment> queue, File file, int kb) {

		this.queue = queue;
		this.file = file;
		this.chunkSize = kb;
	}

	@Override
	public void run() {

		try {

			long currentPosition = 0;
			long totalFileSize = file.length();

			FileChannel inChannel = new FileInputStream(file).getChannel();

			while (currentPosition < totalFileSize) {

				Fragment fragment = new Fragment();

				ByteBuffer chunkBuffer = ByteBuffer.allocate(chunkSize);

				long len = currentPosition + chunkSize < totalFileSize ? chunkSize
						: totalFileSize - currentPosition;

				fragment.setBegin(currentPosition);
				fragment.setFileName(file.getName());

				inChannel.read(chunkBuffer, currentPosition);
				chunkBuffer.flip();

				fragment.setContent(chunkBuffer.array());

				queue.put(fragment);
				
				chunkBuffer.clear();

				currentPosition += len;
			}

			inChannel.close();

		} catch (Exception e) {

			System.err.println("split file error occurs:");
			e.printStackTrace();
		}

	}

}
